
<template>
    <layout title="核酸上门采样服务-10人拼团">
        <div class='wrapper'>
            <van-form>
                <van-field name="applicantName" label="姓名" v-model="formData.applicantName" required placeholder="请输入姓名"
                    @input="$Utils.validateValue(formData, 'applicantName')"
                    :rules="[{ required: true, message: '请输入姓名' }]">

                </van-field>
                <van-field name="applicantPhone" label="电话号码" v-model="formData.applicantPhone" clearble required
                    type="tel" placeholder="请输入电话号码"
                    :rules="[{ required: true, message: '请填写手机号' }, { pattern: /^\d{11}$/, message: '手机号格式错误' }]">

                </van-field>
                <van-field name="userNum" label="检验人数" type="digit" v-model="formData.userNum" required clearable
                    placeholder="请输入检验人数" :rules="[{ required: true, message: '请输入检验人数' }]">

                </van-field>
                <van-field name="endTime" label="拼团截至时间" :value="formData.endTime" required
                    @click="endTimePickerVisible = true" placeholder="请选择拼团截至时间" clearable clear-trigger="always"
                    :rules="[{ required: true, message: '请选择拼团截至时间' }]">

                </van-field>
                <van-field name="applyTime" label="采样时间" :value="formData.applyTime" required
                    @click="applyTimePickerVisible = true" clearable clear-trigger="always" placeholder="请选择采样时间"
                    :rules="[{ required: true, message: '请选择采样时间' }]">

                </van-field>
                <van-field name="city" label="采样省市" :value="cityName" @click="cityPickerVisible = true" clearable 
                    clear-trigger="always" required :rules="[{ required: true, message: '请选择省市' }]"
                    placeholder="请选择采样省市">

                </van-field>
                <van-field name="district" label="区域" :value="districtName" clearable clear-trigger="always" required
                    :rules="[{ required: true, message: '请选择区域' }]" placeholder="请选择区域"
                    @click="districtPickerVisible = true">

                </van-field>
                <van-field name="address" label="详细地址" v-model="formData.adderss" placeholder="请输入详细地址" required
                    clearable clear-trigger="always" type="textarea" show-word-limit maxlength="20"
                    :rules="[{ required: true, message: '请填写详细地址' }]">
                </van-field>
                <van-field name="remakr" label="备注" v-model="formData.remark" placeholder="备注" type="textarea" rows="2"
                    autosize show-word-limit maxlength="50">
                </van-field>
                <van-field name="priceInput" :value="priceInput" label="预计价格" readonly>

                </van-field>
                <div class="btn">
                    <van-button type="info" block round>支 付</van-button>
                </div>
            </van-form>
        </div>

        <!--拼团截至时间弹框  -->
        <van-popup v-model="endTimePickerVisible" round position="bottom">
            <van-datetime-picker v-model="currentDate" title="选择时间" @confirm="confirmEndTime"
                @cancel="endTimePickerVisible = false">

            </van-datetime-picker>
        </van-popup>

        <!--采样时间弹框  -->
        <van-popup v-model="applyTimePickerVisible" round position="bottom">
            <van-datetime-picker v-model="currentDate2" title="选择时间" @confirm="confirmApplyTime"
                @cancel="applyTimePickerVisible = false">

            </van-datetime-picker>
        </van-popup>

        <!-- 城市选择弹框 -->
        <van-popup v-model="cityPickerVisible" round position="bottom">
            <van-picker :columns="cityList" value-key="name" title="选择省市" show-toolbar @confirm="confirmCity"
                @cancel="cityPickerVisible = false">

            </van-picker>
        </van-popup>

        <!-- 区域选择弹框 -->
        <van-popup v-model="districtPickerVisible" round position="bottom">
            <van-picker :columns="districtList" title="选择区域" show-toolbar @confirm="confirmDistrict"
                @cancel="districtPickerVisible = false">

            </van-picker>
        </van-popup>
    </layout>

</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import groupLaunchApi from "@/api/groupLaunch"
export default {
    // import引入的组件需要注入到对象中才能使用
    components: {},
    data() {
        // 这里存放数据
        return {
            openId: "",
            // 当前城市编号
            cityCode: "",
            // 城市名称
            cityName: "",
            // 区域名称
            districtName: "",
            endTimePickerVisible: false,
            applyTimePickerVisible: false,
            cityPickerVisible: false,
            districtPickerVisible: false,
            currentDate: new Date(),
            currentDate2: new Date(),
            cityList: [],
            districtList: [],
            formData: {
                // 拼团人数
                userMin: "",
                hospitalId: "",
                officeId: "",
                doctorId: "",
                applicantName: "",
                applicantPhone: "",
                endTime: "",
                applyTime: "",
                city: "",
                district: "",
                // 检验人数
                userNum: "",
                // 拼团人数
                groupNumber: 10,
                address: "",
                price: "",
                remark: "",
            },

        }
    },
    // 监听属性 类似于data概念
    computed: {
        prices() {
            let value = this.formData.price * this.formData.userNum
            return value ? value : ""
        },
        priceInput() {
            return this.formData.price + "元/人" + "-总计：" + this.prices + "元"
        }
    },
    // 监控data中的数据变化
    watch: {},
    // 方法集合
    methods: {
        init() {
            // this.getCityOptions()
            if (this.$route.query.openId) {
                this.openId = this.$route.query.openId
                if (this.$route.query.state) {
                    let value = decodeURIComponent(this.$route.query.state)
                    let arr = value && value.split(",")
                    this.hospitalId = arr[0]
                    arr.length > 1 ? this.officeId = arr[1] : ""
                    arr.length > 2 ? this.doctorId = arr[2] : ""

                }
                if (this.$route.query.cityName) {
                    let cityName = decodeURIComponent(this.$route.query.cityName)
                    this.cityName = cityName
                    this.getCityOptions()
                }
            }
        },
        // 获取城市
        getCityOptions() {
            switch (this.cityName) {
                case '长沙市':
                    this.cityCode = 0;
                    this.cityList = [{ name: "长沙市", id: 0 }]
                    break;
                case "怀化市":
                    this.cityCode = 1;
                    this.cityList = [{ name: "怀化市", id: 1 }];
                    break;
                case "重庆市":
                    this.cityCode = 2;
                    this.cityList = [{ name: "重庆市", id: 2 }];
                    break;
                case "保定市":
                    this.cityCode = 3;
                    this.cityList = [{ name: "保定市", id: 2 }];
                    break;
                case "北京市":
                    this.cityCode = 5;
                    this.cityList = [{ name: "北京市", id: 2 }];
                    break;
                default:
                    this.cityCode = 4
            }
            this.changeMin(10)
            this.getRegionOptions()
        },
        confirmCity(value) {
            this.cityPickerVisible = false
            this.cityName = value.name
        },
        // 获取区域
        getRegionOptions() {
            switch (this.cityCode) {
                case 0:
                    this.districtList = ["", "岳麓区", "芙蓉区", "天心区", "开福区", "雨花区", "望城区", "长沙县"]; //长沙
                    break;
                case 1:
                    this.districtList = [];//怀化
                    break;
                case 2:
                    this.districtList = ["", "江北区", "沙坪坝区", "大渡口区", "九龙坡区", "南岸区",]; //重庆
                    break;
                case 3:
                    this.districtList = ["", "定兴县", "高碑店市", "白沟新城", "雄安新区"]; //保定
                    break;
                case 5:
                    this.districtList = ["", "海淀区", "丰台区", "朝阳区", "中心城区"]; //北京
                    break;
                case 4:
                    this.districtList = ["", "其他"]
                    break;
                default:
                    this.districtList = []

            }
        },
        confirmDistrict(value) {
            this.districtName = value
            this.districtPickerVisible = false
        },
        confirmEndTime(value) {
            this.formData.endTime = this.$Utils.formatDatetime(value)
            this.endTimePickerVisible = false
        },
        confirmApplyTime(value) {
            this.formData.applyTime = this.$Utils.formatDatetime(value)
            this.applyTimePickerVisible = false



        },
        // 根据成团人数获取价格
        changeMin(val) {  // 成团人数
            console.log(val)
            if (!val) {
                // $.toast("该内容为必填项", "cancel");
                this.$toast({
                    type: "fail",
                    message: "该内容为必填项"
                })
                return
            } else {
                let price = 0;
                if (this.cityValue == 2) {// 重庆
                    console.log("重庆")
                    if (val == 1) {
                        price = 188;
                    } else if (val == 2) {
                        price = 128;
                    } else if (3 <= val && val <= 5) {
                        price = 98;
                    } else if (6 <= val && val <= 8) {
                        price = 78;
                    } else if (val == 9) {
                        price = 68;
                    } else if (val >= 10) {
                        price = 58;
                    }
                } else if (this.cityValue == 3) {   //保定
                    console.log("保定")
                    if (val == 1) {
                        price = 188;
                    } else if (val == 2) {
                        price = 128;
                    } else if (3 <= val && val <= 5) {
                        price = 98;
                    } else if (6 <= val && val <= 8) {
                        price = 78;
                    } else if (val == 9) {
                        price = 68;
                    } else if (val >= 10) {
                        price = 58;
                    }
                } else if (this.cityValue == 4) {   //其他
                    console.log("其他")
                    price = 0;
                } else if (this.cityValue == 5) {   //北京
                    console.log("北京")
                    if (val == 1) {
                        price = 188;
                    } else if (val == 2) {
                        price = 128;
                    } else if (3 <= val && val <= 5) {
                        price = 98;
                    } else if (6 <= val && val <= 8) {
                        price = 78;
                    } else if (val == 9) {
                        price = 68;
                    } else if (val >= 10) {
                        price = 58;
                    }
                } else {//  长沙以及怀化
                    console.log("长沙以及怀化")
                    if (val == 1) {
                        price = 98;
                    } else if (val == 2) {
                        price = 73;
                    } else if (3 <= val && val <= 5) {
                        price = 53;
                    } else if (6 <= val && val <= 8) {
                        price = 48;
                    } else if (val == 9) {
                        price = 43;
                    } else if (val >= 10) {
                        price = 38;
                    }
                }
                this.formData.price = price
            }
        },
        // 微信支付
        wxToPay(collagePayId) {
            var _this = this
            let params = {
                applyId: Number(collagePayId),
                actualPay: Number(_this.prices),
                payType: 1,
            }
            groupLaunchApi.wxPay(params)
                .then(res => {
                    if (res.status == 0) {
                        var payConfig = ret.data;
                        WeixinJSBridge.invoke(
                            'getBrandWCPayRequest', {
                            "appId": payConfig.appId,     //公众号ID，由商户传入
                            "timeStamp": payConfig.timeStamp,         //时间戳，自1970年以来的秒数
                            "nonceStr": payConfig.nonceStr, //随机串
                            "package": payConfig.package,
                            "signType": payConfig.signType,         //微信签名方式
                            "paySign": payConfig.paySign //微信签名
                        },
                            function (res) {
                                //alert(res.err_msg);
                                if (res.err_msg == "get_brand_wcpay_request:ok") {
                                    // 使用以上方式判断前端返回,微信团队郑重提示：
                                    //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                                    // window.open("./group_invitation.html?id=" + collagePayId)
                                    _this.$router.push({
                                        path: "/groupInvitation",
                                        query: {
                                            id: collagePayId
                                        }
                                    })
                                    // 成功了 跳转到详情页
                                } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                                    // 提示用户取消了二维码支付
                                    _this.deleteApply(collagePayId);
                                    _this.$dialog.alert({
                                        title: "提示",
                                        message: "用户取消了支付"
                                    })
                                    // alert("用户取消了支付");
                                    return
                                } else if (res.err_msg == "get_brand_wcpay_request:fail") {
                                    // 提示支付失败
                                    _this.deleteApply(collagePayId);
                                    _this.$dialog.alert({
                                        title: "提示",
                                        message: "支付失败，请重新发起拼团"
                                    })
                                    // alert("支付失败，请重新发起拼团");
                                }
                            });
                    } else {
                        _this.$dialog.alert({
                            title: "提示",
                            message: res.msg
                        })
                    }
                })
                .catch(err => {
                    _this.$dialog.alert({
                        title: "错误",
                        message: err
                    })
                })
        },
        // 
        deleteApply(applyId) {
            let params = {
                id: Number(applyId),
                state: -1
            }
            groupLaunchApi.deleteBoth(params)
                .then(res => {
                    if (res.status != 0) {
                        this.$dialog.alert({
                            title: "提示",
                            message: res.msg
                        })
                    }
                })
        },
        onSubmit() {
            this.formData.applicantName = this.formData.applicantName.replace(/\s/g, "")
            let endTime = new Date(this.formData.endTime)
            let applyTime = new Date(this.formData.applyTime)
            if (!(applyTime - endTime) >= 2 * 60 * 60 * 1000) {
                this.$toast({
                    type: "fail",
                    message: "采样时间至少比拼团截至时间晚两个小时"
                })
                return
            }
            let params = {
                hospitalId: this.formData.hospitalId,
                officeId: this.formData.officeId,
                doctorId: this.formData.doctorId,
                itemName: "新型冠状病毒核酸检测",
                userNum: this.formData.userNum,
                userMin: this.formData.groupNumber,
                itemPrice: this.formData.price,
                payAmount: this.prices,
                applyTime: this.formData.applyTime,
                endTime: this.formData.endTime,
                address: this.formData.address,
                openId: this.openId,
                linkMan: this.formData.applicantName,
                linkPhone: this.formData.applicantPhone,
                remark: this.formData.remark
            }
            groupLaunchApi.addCollage(params)
                .then(res => {
                    if (res.status == 0) {
                        this.wxToPay(res.data)
                    } else {
                        this.$dialog.alert({
                            title: "提示",
                            message: res.msg
                        })
                    }
                })
                .catch(err => {
                    this.$dialog.alert({
                        title: "错误",
                        message: err
                    })
                })

        }
    },
    // 生命周期 - 创建完成（可以访问当前this实例）
    created() {

    },
    // 生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
        this.init()
    },
    beforeCreate() { }, // 生命周期 - 创建之前
    beforeMount() { }, // 生命周期 - 挂载之前
    beforeUpdate() { }, // 生命周期 - 更新之前
    updated() { }, // 生命周期 - 更新之后
    beforeDestroy() { }, // 生命周期 - 销毁之前
    destroyed() { }, // 生命周期 - 销毁完成
    activated() { } // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang="less" scoped>
.wrapper {
    width: 93%;
    background-color: white;
    box-shadow: 0 0 12px rgba(0, 0, 0, 10%);
    border-radius: 10px;
    margin: auto;
    overflow: hidden;

    .btn {
        padding: 20px
    }
}
</style>